//快捷键 rxreducer

import { getToken } from '@/utils/storage';

//1 创建 user reducer
const initialState = {
  // 2.通过getToken获取初始值给auth
  auth: getToken(),
  //17.1.1 定义初始值
  user: {} as UserType,
  //17.2.4 定义 Profile

  profile: {} as ProfileType,
};

export type AuthType = {
  token: string;
  refresh_token: string;
};

//17.1.2 声明类型
export type UserType = {
  id: string;
  name: string;
  photo: string;
  art_count: number;
  follow_count: number;
  fans_count: number;
  like_count: number;
};

//17.2.5 声明类型profile 类型
export type ProfileType = {
  id: string;
  photo: string;
  name: string;
  mobile: string;
  gender: number;
  birthday: string;
  //后台数据没有返回 但是有这个键
  intro: string;
};

type UserAction =
  | {
      type: 'user/saveAuth';
      payload: AuthType;
    }
  // 17.1.3 定义type类型
  | {
      type: 'user/saveUser';
      payload: UserType;
    }
  //17.2.5
  | {
      type: 'user/saveProfile';
      payload: ProfileType;
    }
  //18.1 定义字段
  | {
      type: 'user/updateProfile';
      payload: Partial<ProfileType>;
    };

export default function userReducer(
  state = initialState,
  action: UserAction
): typeof initialState {
  // reducer 处理保存token的计算
  switch (action.type) {
    case 'user/saveAuth':
      return {
        ...state,
        auth: action.payload,
      };
    // 17.1.4 保存逻辑
    case 'user/saveUser':
      return {
        ...state,
        user: action.payload,
      };

    //17.2.6 保存逻辑
    case 'user/saveProfile':
      return {
        ...state,
        profile: action.payload,
      };

    //18.2 更新逻辑 因为不知道更改的是什么字段 所以全部传进来 编写更新保存profile的逻辑
    case 'user/updateProfile':
      return {
        ...state,
        profile: { ...state.profile, ...action.payload },
      };

    default:
      return state;
  }
}
